package com.citms.remote.util;


import com.citms.common.Constant;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class BeanTool {

    private static ObjectMapper MAPPER = new ObjectMapper();

    public static <T> T mapToObject(Map<String, Object> map, Class<T> beanClass){
        if (map == null)
            return null;
        try {
            return  MAPPER.readValue(MAPPER.writeValueAsString(map), beanClass);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("【{}】数据转换错误:{}", Constant.SERVICE_NAME,e.getMessage());
            return null;
        }
    }

    public static Map<?, ?> objectToMap(Object obj) {
        if(obj == null)
            return null;
        try {
            return MAPPER.readValue(objectToJsonStr(obj), HashMap.class);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("【{}】数据转换错误:{}", Constant.SERVICE_NAME,e.getMessage());
            return null;
        }
    }

    public static String objectToJsonStr(Object obj) {
        if(obj == null)
            return null;
        try {
            return MAPPER.writeValueAsString(obj);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("【{}】数据转换错误:{}", Constant.SERVICE_NAME,e.getMessage());
            return null;
        }
    }
}
